package com.amon.amonplayer;

import android.os.Handler;
import android.os.Looper;

public class LivePush {
    static {
        System.loadLibrary("rtmp");
    }

    private static final Handler MAIN_HANDLER = new Handler(Looper.myLooper());

    private final String mPushUrl;
    private ConnectListener mConnectListener;

    public LivePush(String pushUrl) {
        this.mPushUrl = pushUrl;
    }

    public void initConnect() {
        nInitConnect(mPushUrl);
    }

    private void onConnectError(int errCode, String msg) {
        stop();
        if (mConnectListener != null) {
            mConnectListener.OnConnectError(errCode, msg);
        }
    }

    public void stop() {
        MAIN_HANDLER.post(this::nStop);
    }

    private void onConnectSuccess() {
        if (mConnectListener != null) {
            mConnectListener.OnConnectSuccess();
        }
    }

    public void setOnConnectListener(ConnectListener listener) {
        mConnectListener = listener;
    }

    public native void pushSpsPps(byte[] mVideoSps, int spsLength, byte[] mVideoPps, int ppsLength);

    public native void pushVideo(byte[] videoData, int length, boolean keyFrame);

    public native void pushAudio(byte[] audioData, int length);

    public native void startService();

    public interface ConnectListener {
        void OnConnectError(int code, String msg);

        void OnConnectSuccess();
    }

    private native void nStop();

    private native void nInitConnect(String url);
}
